package com.lanqiao.guimei.commons;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.Converter;

import javax.servlet.annotation.WebListener;

/**
 * <input type="text|date" value="2000-09-11">  ---> vo.XxxEntity#Date birthdate;
 * BeanUtils.populate(target, source);
 *
 *
 * // 在监听器中注册类型转换器
 * CustomDateTimeConverter dateTimeConverter = new CustomDateTimeConverter();
 * ConvertUtils.register(dateTimeConverter, java.util.Date.class);
 * ConvertUtils.register(dateTimeConverter, java.sql.Date.class);
 * //ConvertUtils.register(dateTimeConverter, java.sql.Timestamp.class);
 */
public class CustomDateTimeConverter implements Converter {
	
	private static String[] patterns = new String[]{"yyyy年MM月dd日 hh:mm:ss",
													"yyyy-MM-dd HH:mm:ss",
													"yyyy/MM/dd HH:mm:ss",
													"yyyy-MM-dd",
													"yyyy年MM月dd日",
													"yyyyMMdd"};

	/**
	 * @param type 转换的目标类型
	 * @param value 要转换的值
	 */
	public Object convert(Class type, Object value) {
		// TODO Auto-generated method stub
		if (value == null) {
			/*if (type == Date.class) {
				return new Date();
			} else if (type == java.sql.Date.class) {
				return new java.sql.Date(new Date().getTime());
			}*/
			return null;
		} else {
			// 要转换的值非空
			String orgValue = value.toString();
			if (type == Date.class) {
				return toUtilDate(orgValue);
				
			} else if (type == java.sql.Date.class) {
				return toSqlDate(orgValue);
			}
		}
		return null;
	}
	

	/**
	 * 转换成java.sql.Date
	 * @param value 字符串
	 * @return
	 */
	private Date toUtilDate(String value){
		SimpleDateFormat sdf = null;
		for (String pattern  : patterns) {
			sdf = new SimpleDateFormat(pattern);
			try {
				return sdf.parse(value);
			} catch (ParseException e) {
				continue;
			}
		}
		return null;
	}
	
	/**
	 * 转换成java.sql.Date
	 * @param value 字符串
	 * @return
	 */
	private java.sql.Date toSqlDate(String value){
		Date d = toUtilDate(value);
		return d != null ? new java.sql.Date(d.getTime()) : null;
	}

	
}
